package com.lyx.controller;

import com.lyx.domain.Permission;
import com.lyx.domain.Role;
import com.lyx.domain.UserInfo;
import com.lyx.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

//角色控制器
@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    //查询所有
    @RequestMapping("/findAll.do")
    @RolesAllowed({"USER", "ADMIN"})
    public ModelAndView findAll() throws Exception{
        ModelAndView mv = new ModelAndView();
        List<Role> roleList = roleService.findAll();
        mv.addObject("roleList", roleList);
        mv.setViewName("role-list");
        return mv;
    }

    //保存
    @RequestMapping("/save.do")
    @Secured("ROLE_ADMIN")
    public String save(Role role) throws Exception{
        roleService.save(role);
        return "redirect:findAll.do";
    }

    //删除
    @RequestMapping("/deleteRole.do")
    public String deletePermission(@RequestParam(name = "id", required = true)String id) throws Exception{
       roleService.deleteRoleById(id);
        return "redirect:findAll.do";
    }

    //根据id查询
    @RequestMapping("/findById.do")
    public ModelAndView findById(@RequestParam(name = "id", required = true)String id) throws Exception{
        ModelAndView mv = new ModelAndView();
        Role role=roleService.findById(id);
        mv.addObject("role", role);
        mv.setViewName("role-show");
        return mv;
    }

    //查询角色未添加的权限
    @RequestMapping("/findRoleByIdAndAllPermission.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id",required = true) String id) throws Exception{
        ModelAndView mv=new ModelAndView();
        Role role=roleService.findById(id);
        List<Permission> permissionList =roleService.findOtherPermissions(id);
        mv.addObject("role", role);
        mv.addObject("permissionList",permissionList);
        mv.setViewName("role-permission-add");
        return mv;
    }

    //角色关联权限
    @RequestMapping("/addPermissionToRole.do")
    public String addRoleToUser(@RequestParam(name = "roleId",required = true) String roleId,@RequestParam(name = "ids",required = true) String []permissionIds) throws Exception {
        roleService.addPermissionToRole(roleId,permissionIds);
        return "redirect:findAll.do";
    }
}
